package com.example.weddingapp.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.AndroidViewModel;

import com.example.weddingapp.R;
import com.example.weddingapp.adapter.OrderAdapter;
import com.example.weddingapp.base.BaseFragment;
import com.example.weddingapp.base.BaseObserver;
import com.example.weddingapp.databinding.FragmentAccountBinding;
import com.example.weddingapp.utils.CommonUtil;
import com.example.weddingapp.utils.RefreshHelper;

import java.util.List;

import cn.leancloud.AVObject;
import cn.leancloud.AVQuery;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.jingbin.library.ByRecyclerView;
import me.jingbin.library.decoration.SpacesItemDecoration;


/**
 * @Date 2020/5/15 0:45
 * @Desc 流水
 */
public class AccountFragment extends BaseFragment<AndroidViewModel, FragmentAccountBinding> implements View.OnClickListener {
    private OrderAdapter adapter;
    private int page = 1;
    private int pageSize = 30;

    @Override
    public int setContent() {
        return R.layout.fragment_account;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showContentView();
        initRecyclerView();
        showLoading();


        getData();

    }

    @Override
    public void onResume() {
        super.onResume();
        getShouRu();
    }

    @Override
    public void onClick(View v) {
    }

    private void initRecyclerView() {
        adapter = new OrderAdapter(getContext());
        // 加了分割线，滚动条才会置顶
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(getContext(), SpacesItemDecoration.VERTICAL, 1);
        //xrvAndroid是fragment_android中ByRecyclerView的id名xrv_android
        RefreshHelper.initLinear(bindingView.recyclerView, false).addItemDecoration(itemDecoration);
        bindingView.recyclerView.setAdapter(adapter);
        bindingView.recyclerView.setOnRefreshListener(new ByRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }
        });
        bindingView.recyclerView.setOnLoadMoreListener(new ByRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                getData();
            }
        }, 300);

        bindingView.recyclerView.setOnItemClickListener(new ByRecyclerView.OnItemClickListener() {
            @Override
            public void onClick(View v, int position) {
                AVObject object = adapter.getData().get(position);
//                Intent intent = new Intent(getContext(), PersonalCenterActivity.class);
//                startActivity(intent);


            }
        });
    }


    private void getShouRu() {
        AVQuery<AVObject> query = new AVQuery<>("Order");
        query.whereEqualTo("fromUser", AVUser.currentUser());
        query.findInBackground().subscribe(new BaseObserver<List<AVObject>>() {
            @Override
            public void onNext(List<AVObject> list) {
                super.onNext(list);
                int valueAdd = 0, shouru = 0, zhichu = 0;
                for (AVObject object : list) {
                    String action = object.getString("action");
                    int intMoney = object.getInt("intMoney");
                    if ("充值".equals(action)) {
                        valueAdd += intMoney;
                    } else if ("送礼".equals(action)) {
                        zhichu += intMoney;
                    } else {
                        shouru += intMoney;
                    }

                    Double value1 = Double.valueOf(valueAdd) / 100;
                    Double value2 = Double.valueOf(shouru) / 100;
                    Double value3 = Double.valueOf(zhichu) / 100;
                    String str1 = CommonUtil.formatAmount(value1);
                    String str2 = CommonUtil.formatAmount(value2);
                    String str3 = CommonUtil.formatAmount(value3);

                    bindingView.tvValueAdd.setText("充值统计：" + str1);
                    bindingView.tvShouru.setText("收礼统计：" + str2);
                    bindingView.tvZhichu.setText("送礼统计：" + value3);
                }
            }
        });
    }

    private void getData() {
        if (page == 1) {
            adapter.clear();
            adapter.notifyDataSetChanged();
        }
        AVQuery<AVObject> query = new AVQuery<>("Order");
        query.include("toUser");
        query.include("fromUser");
        query.whereEqualTo("fromUser", AVUser.currentUser());
        // 按 createdAt 降序排列
        query.orderByDescending("createdAt");
        // 最多获取 pageSize 条结果
        query.limit(pageSize);
        // 跳过前 pageSize 条结果
        query.skip((page - 1) * pageSize);
        query.findInBackground().subscribe(new Observer<List<AVObject>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<AVObject> list) {
                showContentView();
                if (list != null && list.size() > 0) {
                    if (page == 1) {
                        showContentView();
                        adapter.setNewData(list);
                    } else {
                        adapter.addData(list);
                    }
                    bindingView.recyclerView.loadMoreComplete();
                    if (list.size() < pageSize) {
                        bindingView.recyclerView.loadMoreEnd();
                    }
                } else {
                    if (page == 1) {
                        showToast("暂无数据");
                    } else {
                        bindingView.recyclerView.loadMoreEnd();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                showContentView();
                showToast("暂无数据");
            }

            @Override
            public void onComplete() {

            }
        });
    }
}